<?php
namespace app\admin\controller;
use think\Db;
class Article extends Base
{   
    public function lists(){

        $rec        = new \app\admin\model\ArticleRec();
        $rec_list   = $rec->lists(0);#推荐位
        
        //ajax查询数据
        if( is_post() ){
            $page     = input('page');
            $cat_id   = input('cat_id');
            $rec_id   = input('rec_id');
            $status   = input('status');
            $keyword  = input('keyword');
            $min_time = input('min_time');
            $max_time = input('max_time');
            
            //原生态sql查询
            $sql = "
                select
                    [1]
                from
                    article a
                left join
                    article_cat ac
                on
                    a.cat_id=ac.id
                where 
                    1 = ?
                ";
            $param = [1];
            if ( $cat_id != '100all' ) {
                $sql .= " and a.cat_id = ?";
                $param[] = $cat_id;
            }
            if ( $rec_id != '100all' ) {
                $sql .= " and a.rec_id = ?";
                $param[] = $rec_id;
            }
            if ( $status != '100all' ) {
                $sql .= " and a.status = ?";
                $param[] = $status;
            }
            if ( !empty($keyword) ) {
                $sql .= " and a.title like ?";
                $param[] = "%{$keyword}%";
            }
            if ( !empty($min_time) ) {
                $sql    .= " and a.create_time >= ?";
                $param[] = strtotime($min_time);
            }
            if ( !empty($max_time) ) {
                $sql    .= " and a.create_time <= ?";
                $param[] = strtotime($max_time);
            }
            //总条数
            $sql_count = str_replace("[1]", "count(*) as total", $sql);
            $total     = Db::query($sql_count, $param);
            $total     = $total[0]['total'];
            
            //分页数据
            $page_size   = c('page_size');     #分页条数
            $page        = com_cur_page($total, $page,  $page_size);   #当前页
			$page_data   = com_page_data($total, $page,  $page_size);   #分页原始数据
            
            //列表数据
			$start       = ($page - 1) * $page_size;
			$sql        .= " order by a.sort desc, a.id desc limit $start, $page_size";
			$field       = "a.*, ac.cat_title";
			$sql_list    = str_replace("[1]", $field, $sql);
            $list        = Db::query($sql_list, $param);
            
            //格式数据
            foreach($list as $k => $v){                
                $list[$k]['checkbox']       =  com_format_checkbox($v['id']);
                $list[$k]['create_time']    =  com_format_time( $v['create_time'] );
                $list[$k]['pic']            =  com_format_pic(com_get_pic($v['pic'],'small'));
                
                $rs                         =  [0=>'无推荐位'] + $rec_list;
                $list[$k]['rec_id']         =  com_format_select_edit( $v['rec_id'], $rs, url('article/editRec'), $v['id'] );
                $list[$k]['views']          =  com_format_input_edit(url('article/editViews'), $v['id'], $v['views']);
                $list[$k]['sort']           =  com_format_input_edit(url('ajax/editSort', 't=article'), $v['id'], $v['sort']);
                
                $list[$k]['status']         =  com_format_status2(url('ajax/editStatus', 't=article'),$v['id'],$v['status']);

                //操作按钮
                $list[$k]['action']         =  com_action_edit( url("article/edit","id={$v['id']}"), $v['id'], '编辑文章' );
                $list[$k]['action']        .=  com_action_copy( url('ajax/copy','t=article'), $v['id'], "你确定要拷贝[{$v['title']}]吗?" );
                $list[$k]['action']        .=  com_action_del( url("ajax/delete","t=article"), $v['id'], "你确定要删除{$v['title']}吗？" );
                
                
            }
			$com_body    = com_build_table($list, array("checkbox","id","title", "cat_title","pic", "views", "sort","status" , "rec_id","create_time", "action"));
			$com_page    = com_build_page( $page_data );
			$data = array(
				"com_body"  => $com_body,
				"com_page"  => $com_page,
			);
            $config = [
                'data'   => $data,
                'suc'    => [
                    'js_action' => 'function.switchs',
                ],
            ];
			com_check($config);
        }        
        $all= [
            '100all' => [
                'id' => '100all',
                'parent_id' => 0,
                'cat_title' => '全部分类',
                'depath' => 0,
                ]
        ];
        $category = $all + \app\admin\model\ArticleCat::allSubCat();
        $data = [
            'category'  => $category,
            'rec'       => ['100all'=>'全部推荐'] + $rec_list,
            'status'    => ['100all'=>'全部状态'] + c('type.status'),
            'nav'       => ['文章管理', '列表'],
        ];
        return view('', $data);
    }
    
    //编辑阅读量
    public function editViews(){
        if( is_post() ){
            $data   = [
                'id'    => input('id'),
                'views' => (int)input('val'),
            ];
            \app\admin\model\Article::update($data);
            $config = [
                'suc' => [
                    'msg' => '编辑浏览量成功！',
                    'js_action' => 'alert',
                ],
            ];
            com_check($config);
        }
    }
    
    //编辑推荐位
    public function editRec(){
        if( is_post() ){
            $data   = [
                'id'        => input('id'),
                'rec_id'    => (int)input('val'),
            ];
            \app\admin\model\Article::update( $data );
            
            $config = [
                'suc' => [
                    'msg' => '编辑推荐位成功！',
                    'js_action' => 'alert',
                ],
            ];
            com_check( $config );
        }
    }
    
    //添加
    public function add(){
        if( is_post() ){
            $data = input();  #post数据
            unset($data['pic']);
            unset($data['input-file']);
            //验证
            $rule = [
                'title'      =>  'require',
                'sort'       =>  'require',
                'cat_id'     =>  'number',
                'views'      =>  'require',
            ];
            $msg = [
                'title.require'      =>  '标题不能为空',
                'sort.require'       =>  '排序值不能为空',
                'cat_id.number'      =>  '请选择分类',
                'views.require'      =>  '阅读量不能为空',
            ];
            com_validate( $rule, $msg, $data, true );
            //文件上传
            if( isset($_FILES['pic']) ){
                $pic = com_up_pic('article', 'pic', true);
                com_check( ['err'=>['js_action'=>'alert'], 'suc'=>['return_type'=>'return']]);
                $data['pic'] = $pic;
            }
            $article  = new \app\admin\model\Article();
            $article->save($data);
            $config = [
                'msg' => '添加文章成功！',
                'suc' => [
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        }    
        //模板赋值
        $rec    = new \app\admin\model\ArticleRec();
        $ac     = new \app\admin\model\ArticleCat();
        $all= [
            '100all' => [
                'id' => '100all',
                'parent_id' => 0,
                'cat_title' => '请选择分类',
                'depath' => 0,
                ]
        ];
        $category = $all + $ac::allSubCat();
        $data = [
            'category'  => $category,
            'rec'       => array_merge([0=>'无推荐位'], $rec->lists(0)),
            'status'    => c('type.status'),
        ];
        return view('', $data);
    }
    
    
    //编辑
    public function edit( $id ){
        if( is_post() ){
            $data = input();  #post数据
            unset($data['pic']);
            unset($data['input-file']);
            //验证
            $rule = [
                   'title'      =>  'require',
                   'sort'       =>  'require',
                   'views'      =>  'require',
                ];
            $msg = [
                   'title.require'      =>  '标题不能为空',
                   'sort.require'       =>  '排序值不能为空',
                   'views.require'      =>  '阅读量不能为空',
                ];
            com_validate( $rule, $msg, $data, true );
            
            if( isset($_FILES['pic']) ){
                $pic = com_up_pic('article', 'pic', true);
                $data['pic'] = $pic;
                com_check(['err'=>['js_action'=>'alert'], 'suc'=>['return_type'=>'return']] );
            }
            if( isset($data['delete_pic']) ){
                unset($data['delete_pic']);
                if(!isset($_FILES['pic'])) $data['pic'] = '';

            }
            $data['id'] = $id;
            \app\admin\model\Article::update($data);
            $config = [
                'suc' => [
                    'msg' => '编辑文章成功！',
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        }
        $rec    = new \app\admin\model\ArticleRec();
        $info   = \app\admin\model\Article::get($id)->getData();
        $data = [
            'category'  => \app\admin\model\ArticleCat::allSubCat(),
            'rec'       => array_merge([0=>'无推荐位'], $rec->lists(0)),
            'status'    => c('type.status'),
            'info'      => $info,
        ];
        return view('', $data);
    }
    
    
    //批量删除
    public function delall(){
        if( is_post() ){
            \app\admin\model\Article::destroy( implode(",", input('ids/a')) );
            $config = [
                'suc' => [
                    'msg' => '删除成功！',
                    'js_action'=>"alert|reload",
                ],
            ];
            com_check($config);
        }
    }
}